package com.asiainfo.argumentResolver;

import com.asiainfo.annotation.RequestParam;
import com.asiainfo.annotation.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Service("argumentResolverParamImpl")
public class ArgumentResolverParamImpl implements IArgumentResolver {
    /**
     * 判断参数是不是requestParam
     *
     * @param type
     * @param paramIndex
     * @param method
     * @return
     */
    @Override
    public boolean support(Class<?> type, int paramIndex, Method method) {
        //获得当前方法的参数
        Annotation[][] an = method.getParameterAnnotations();
        Annotation[] paramAns = an[paramIndex];
        for (Annotation paramAn : paramAns) {
            //如果是requestParam 返回true
            if (RequestParam.class.isAssignableFrom(paramAn.getClass())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 返回第几个参数的值
     *
     * @param request
     * @param response
     * @param type
     * @param paramIndex
     * @param method
     * @return
     */
    public Object argumentResolver(HttpServletRequest request, HttpServletResponse response, Class<?> type, int paramIndex, Method method)
    {
        Annotation[][] an = method.getParameterAnnotations(); //获得参数的注解
        Annotation[] paramAns = an[paramIndex];
        for (Annotation paramAn : paramAns)
        {
            if (RequestParam.class.isAssignableFrom(paramAn.getClass()))
            {
                RequestParam requestParam = (RequestParam) paramAn;
                String value = requestParam.value();
                return request.getParameter(value); //返回对应的值
            }
        }
        return null;
    }
}
